import { Component, OnInit } from '@angular/core';
import { PaginationModel } from 'app/widgets/pagination';
import { environment } from '../../../../../environments/environment';
import { StopfundPageService } from "./stop-fund-page.service";
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js";
import * as _ from 'lodash';
import { DataService } from '../../../../services/data.service';
//updated by dujh @20180627 start
import { Util } from 'app/common/util';
//updated by dujh @20180627 end
@Component({
  selector: 'app-stop-fund-page',
  templateUrl: './stop-fund-page.component.html',
  styleUrls: ['./stop-fund-page.component.scss'],
  providers: [StopfundPageService]
})
export class StopFundPageComponent implements OnInit {

  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 分页列表post
  public getBody = {
    pageIndex: 1,
    pageSize: 10,
    sBegin: '',
    sEnd: '',
    logStatus: '',
    idList: '',
    sFundName: '',
    sFundCode: ''
  };
  // 分页配置
  public listPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  // 分页列表数据
  public dataList: any;
  // 列表全选
  public isCheckedAll: any = false;
  // 账户列表
  public accountList: any;
  // 产品账户Id
  public accountId: any;
  // 手工录入列表
  public inputList: any = [];
  // 手工录入模版
  public inputModel: any = [
    { 'nFundNo': '', 'logDate': '', 'logMemo': '', 'logDebetAmount': '', 'logCreditAmount': '', 'logStatus': '未完结' },
    { 'nFundNo': '', 'logDate': '', 'logMemo': '', 'logDebetAmount': '', 'logCreditAmount': '', 'logStatus': '未完结' },
    { 'nFundNo': '', 'logDate': '', 'logMemo': '', 'logDebetAmount': '', 'logCreditAmount': '', 'logStatus': '未完结' },
    { 'nFundNo': '', 'logDate': '', 'logMemo': '', 'logDebetAmount': '', 'logCreditAmount': '', 'logStatus': '未完结' },
    { 'nFundNo': '', 'logDate': '', 'logMemo': '', 'logDebetAmount': '', 'logCreditAmount': '', 'logStatus': '未完结' },
    { 'nFundNo': '', 'logDate': '', 'logMemo': '', 'logDebetAmount': '', 'logCreditAmount': '', 'logStatus': '未完结' },
    { 'nFundNo': '', 'logDate': '', 'logMemo': '', 'logDebetAmount': '', 'logCreditAmount': '', 'logStatus': '未完结' },
    { 'nFundNo': '', 'logDate': '', 'logMemo': '', 'logDebetAmount': '', 'logCreditAmount': '', 'logStatus': '未完结' },
    { 'nFundNo': '', 'logDate': '', 'logMemo': '', 'logDebetAmount': '', 'logCreditAmount': '', 'logStatus': '未完结' },
    { 'nFundNo': '', 'logDate': '', 'logMemo': '', 'logDebetAmount': '', 'logCreditAmount': '', 'logStatus': '未完结' }
  ];
  // 修改body
  public editBody: any = {};

  constructor(
    public stopfundPageService: StopfundPageService,
    public dataService: DataService
  ) { }

  ngOnInit() {
    // 初始化日期控件
    flatpickr.localize(zh);
    // 权限处理
    let that = this;
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData)
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '综合查询') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == '终止后资金流水查询') {
                that.menuResourceSet = it.resourceSet
                sessionStorage.setItem('btn-productInfo', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '综合查询') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '终止后资金流水查询') {
            that.menuResourceSet = it.resourceSet
            sessionStorage.setItem('btn-productInfo', this.menuResourceSet);
          }
        })
      }
    })
    this.getAccountList();
    this.list();
  }
  ngAfterViewInit() {
    let that = this;
    setTimeout(function () {
      window['$']('.account').select2({ width: '180px' });
      window['$']('.account').on("select2:select", function (e) {
        that.accountId = window['$']('.account').select2("val");
        // 重置空模版
        that.inputList = [];
        // 重置默认模版
        _.forEach(that.inputModel, item => {
          item.nFundNo = that.accountId;
          item.isChecked = false;
          item.logDate = '';
          item.logMemo = '';
          item.logDebetAmount = '';
          item.logCreditAmount = '';
          item.logStatus = '未完结';
        });
        that.stopfundPageService.checkAccount(that.accountId).subscribe(data => {
          // 存在已完结流水基金
          if (data == true) {
            window['swal']({
              type: "warning",
              showCancelButton: true,
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              closeOnConfirm: true,
              showLoaderOnConfirm: false,
              title: "提示",
              text: "该账户已有已完结流水资金,是否继续?",
              html: true
            },
              function (isConfirm) {
                if (isConfirm) {
                  that.inputList = that.inputModel;
                }
              })
          } else {
            that.inputList = that.inputModel;
          }
        })
      });
    }, 300);
  }
  // 分页列表
  list(pageNum?, pageSize?) {
    //updated by dujh @20180702 start
    if (!Util.dateOrder(this.getBody.sBegin, this.getBody.sEnd)) {
      window['swal']("提示", "开始日期必须早于结束日期", "warning");
      return;
    }
    //updated by dujh @20180702 end
    let that = this;
    this.isCheckedAll = false;
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.getBody.sFundCode = _.trim(this.getBody.sFundCode);
    this.getBody.sFundName = _.trim(this.getBody.sFundName);
    this.stopfundPageService.list(this.getBody).subscribe(data => {
      if (data) {
        that.dataList = data.list;
        _.forEach(that.dataList, item => {
          if (!isNaN(item.logDebetAmount)) {
            item.logDebetAmount = item.logDebetAmount.toFixed(2);
          }
          if (!isNaN(item.logCreditAmount)) {
            item.logCreditAmount = item.logCreditAmount.toFixed(2);
          }
          if (!isNaN(item.logBalance)) {
            item.logBalance = item.logBalance.toFixed(2);
          }
        })
        that.listPageInfo.currentPageNum = data.pageNum;
        that.listPageInfo.totalPages = data.pages;
        that.listPageInfo.total = data.total;
        that.listPageInfo.startRow = data.startRow;
        that.listPageInfo.endRow = data.endRow;
      }
    });
  }
  //个数分页
  listPageSizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.list(1);
    }
  }
  // 条数分页
  listPageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.list(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      _.forEach(this.dataList, item => {
        item.isChecked = true;
      });
    } else {
      _.forEach(this.dataList, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.dataList, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.dataList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 导出
  exportExcel() {
    let that = this;
    let idList = [];
    _.forEach(that.dataList, item => {
      if (item.isChecked) {
        idList.push(item.id);
      }
    })
    // let converItem: any = checkedItem.join(',');
    let getBody = {
      "idList": idList,
      "sBegin": this.getBody.sBegin,
      "sEnd": this.getBody.sEnd,
      "sFundCode": this.getBody.sFundCode,
      "sFundName": this.getBody.sFundName,
      "logStatus": this.getBody.logStatus
    }
    const iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    //  转码，兼容ie
    getBody.sFundCode = encodeURI(getBody.sFundCode);
    getBody.sFundName = encodeURI(getBody.sFundName);
    getBody.logStatus = encodeURI(getBody.logStatus);
    iframe.attr('src', environment.server + '/pms/v1/productquery/export/exportAccountCloseCapital?token=' + sessionStorage.getItem('token') + '&idList=' + getBody.idList + '&sBegin=' + getBody.sBegin + '&sEnd=' + getBody.sEnd + '&sFundCode=' + getBody.sFundCode + '&sFundName=' + getBody.sFundName + "&logStatus=" + getBody.logStatus);
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 2 * 60000);
  }
  // 获取产品账户列表
  getAccountList() {
    let that = this;
    this.stopfundPageService.getAccountList().subscribe(data => {
      if (data) {
        that.accountList = data;
      }
    })
  }
  // 手工录入model
  showInput() {
    // 重置空模版
    this.inputList = [];
    // 清空下拉框值
    this.accountId = '';
    // 重新刷新账户列表，解决重新打开modal账户数据无法清空问题
    window['$']('.account').select2("val", "--请选择--");
    // this.getAccountList();
    window['$']('#input').modal('show');
  }
  // 手工录入保存
  saveInput() {
    let that = this;
    // 用于保存需要提交的item
    let saveItem = [];
    // 用于保存没有填写日期或摘要的item
    let tipsItem = [];
    _.forEach(this.inputList, item => {
      if (item.isChecked) {
        // 勾选的不做处理
      } else {
        if (item.logDate == '' || item.logMemo == '') {
          tipsItem.push(item);
        }
        saveItem.push(item);
      }
    });
    if (tipsItem.length > 0) {
      window['swal']("提示", "日期和摘要不可为空", "warning");
    } else {
      if (saveItem.length > 0) {
        _.forEach(saveItem, it => {
          delete it.isChecked;
        });
        this.stopfundPageService.add(saveItem).subscribe(data => {
          if (data) {
            window['$']('#input').modal('hide');
            window['swal']("成功", "录入成功", "success");
            that.list();
          }
        })
      } else {
        window['swal']("提示", "请填入有效数据", "warning");
      }
    }
  }
  // 修改model
  showEdit() {
    let that = this;
    let checkedItem = [];
    _.forEach(this.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item);
      }
    });
    if (checkedItem.length == 1) {
      this.editBody = _.clone(checkedItem[0]);
      window['$']('#edit').modal('show');
    } else {
      window['swal']("提示", "请选择一条数据进行修改", "warning");
    }
  }
  // 修改保存
  saveEdit() {
    let that = this;
    if (this.requiredEdit()) {
      // 去除不需传字段
      delete this.editBody.sFundName;
      delete this.editBody.sFundCode;
      delete this.editBody.sFundType;
      delete this.editBody.sFundTypeZh;
      delete this.editBody.logStatusZh;
      delete this.editBody.isChecked;
      this.stopfundPageService.edit(this.editBody).subscribe(data => {
        if (data) {
          window['$']('#edit').modal('hide');
          window['swal']("成功", "修改成功", "success");
          that.list();
        }
      })
    }
  }
  // 修改必填校验
  requiredEdit() {
    let that = this;
    let requiredEditTip = [];
    let logDate = _.trim(this.editBody.logDate);
    let logMemo = _.trim(this.editBody.logMemo);
    if (logDate == '' || logDate == null) {
      requiredEditTip.push("日期");
    }
    if (logMemo == '' || logMemo == null) {
      requiredEditTip.push("摘要");
    }
    if (requiredEditTip.length > 0) {
      let requiredEditTips = requiredEditTip.join("、");
      window['swal']("提示", "请填写:" + requiredEditTips, "warning");
      return false;
    } else {
      return true;
    }
  }
  // 删除
  del() {
    let that = this;
    let checkedItem = [];
    let checkedFundName = [];
    _.forEach(this.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item.id);
        checkedFundName.push(item.sFundName);
      }
    })
    let checkedTips = checkedFundName.join("、");
    if (checkedItem.length > 0) {
      window['swal']({
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        showLoaderOnConfirm: true,
        title: "提示",
        text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否删除：" + checkedTips + "组合" + "</div>",
        html: true
      }, function (isConfirm) {
        if (isConfirm) {
          let putBody: any = {
            "idList": checkedItem
          }
          that.stopfundPageService.del(putBody).subscribe(data => {
            if (data) {
              window['swal']("删除成功！", '', "success")
              that.list();
            }
          })
        }
      })
    } else {
      window['swal']("提示", "请选择一个或多个数据进行删除", "warning");
    }
  }
  // 过滤两位小数,i为下标,key为字段名,value为修改后的值
  filterNumber(i: any, key: any, value: any, type: any) {
    let that = this;
    if (value != '' && value != null && value != undefined) {
      switch (key) {
        case 'logDebetAmount':
          if (type == '手工录入') {
            that.inputList[i].logDebetAmount = parseFloat(value).toFixed(2);
          } else if (type == '修改') {
            that.editBody.logDebetAmount = parseFloat(value).toFixed(2);
          }
          break;
        case 'logCreditAmount':
          if (type == '手工录入') {
            that.inputList[i].logCreditAmount = parseFloat(value).toFixed(2);
          } else if (type == '修改') {
            that.editBody.logCreditAmount = parseFloat(value).toFixed(2);
          }
          break;
      }
    }
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.dataList, [colName], ["asc"]);
    if (JSON.stringify(this.dataList) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.dataList, [colName], ["desc"]);
    }
    this.dataList = listDataAsc;
  }
}
